package com.my.servlet;

import com.alibaba.fastjson.JSON;
import com.my.controal.JDBC;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/RegisterUser")
public class RegisterUser extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 处理中文乱码
        response.setContentType("application/json;charset=utf-8");
        response.setCharacterEncoding("UTF-8");

        String userID = request.getParameter("userID");
        String password = request.getParameter("password");
        String name = request.getParameter("name");
        String IDcard = request.getParameter("IDcard");
        String tel = request.getParameter("tel");

        // 在进行注册之前判断是否存在当前待插入ID
        String sql2 = String.format("SELECT tb_user.userID FROM tb_user WHERE tb_user.userID = '%s'", userID);

        String flag; // 插入是否成功
        try {
            // 判断是否待插入ID
            ResultSet res = JDBC.Instance().selectTable(sql2);
            if(res.next()) {
                flag = "0";
            }
            else {
                String sql = String.format("INSERT INTO tb_user VALUES('%s', '%s', '%s', '%s', '%s')", userID, password, name, IDcard, tel);

                JDBC.Instance().querySQLCommand(sql);

                // 插入是否插入成功
                String sql1 = String.format("SELECT tb_user.userID FROM tb_user WHERE tb_user.userID = '%s'", userID);
                ResultSet res1 = JDBC.Instance().selectTable(sql1);

                // 插入成功， 返回至前台页面，前台页面输出注册成功
                if (res1.next()) {
                    flag = "1";
                }
                else {
                    flag = "0";
                }
            }


            String str = JSON.toJSONString(flag);
            response.getWriter().print(str);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
